package com.ihr360.expr.engine;

import com.ihr360.expr.ExprBoolean;
import com.ihr360.expr.ExprError;
import com.ihr360.expr.ExprException;
import com.ihr360.expr.ExprMissing;
import com.ihr360.expr.context.IEvaluationContext;
import com.ihr360.expr.core.Expr;
import com.ihr360.expr.core.ExprFunction;
import com.ihr360.expr.core.ExprVariable;
import com.ihr360.expr.function.ExcelFunctionProvider;
import com.ihr360.expr.function.FunctionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


public class BasicEngineProvider implements EngineProvider {
	Logger logger = LoggerFactory.getLogger(BasicEngineProvider.class.getName());
	private FunctionManager functions = new FunctionManager();
	private Map<String, Expr> variables = new HashMap<>();

	public BasicEngineProvider() {
		functions.add(new ExcelFunctionProvider());
		//额外的变量，使用于公共的变量定义
		variables.put("TRUE", ExprBoolean.TRUE);
		variables.put("FALSE", ExprBoolean.FALSE);
	}

	@Override
	public void inputChanged(VariableID range, Expr input) {
		if (logger.isDebugEnabled()){
			logger.debug("Input changed: {} =\n {}" ,range,input);
		}
	}

	@Override
	public void valueChanged(VariableID range, Expr value) {
		if (logger.isDebugEnabled()){
			logger.debug("Value changed: {} =\n {}", range, value);
		}
	}

	@Override
	public void validate(ExprVariable variable) throws ExprException {

	}
	@Override
	public Expr evaluateFunction(IEvaluationContext context,
			ExprFunction function) throws ExprException {
		return functions.evaluate(context,function);
	}
	@Override
	public Expr evaluateVariable(IEvaluationContext context,
			ExprVariable variable) throws ExprException {
		String name = variable.getName().toUpperCase();
		if (variables.containsKey(name)) {
			return variables.get(name);
		}
		Expr e = variables.get(name);
		if (e == null){
			return ExprError.NAME;
		}
		return e;
	}

	@Override
	public Expr notifyMissing(ExprVariable variable) {
		return ExprMissing.MISSING;
	}
}